package com.hmdp.utils;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.hmdp.entity.Shop;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

import static com.hmdp.utils.RedisConstants.*;

@Slf4j
@Component
public class CacheClient {
    //构造函数注入bean
    private final StringRedisTemplate stringRedisTemplate;
    //构造函数注入bean
    public CacheClient(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    //（缓存穿透）写入缓存
    public void set(String key, Object value, Long time, TimeUnit unit){
        String jsonStr = JSONUtil.toJsonStr(value);
        stringRedisTemplate.opsForValue().set(key,jsonStr,time,unit);
    }
    //设置逻辑过期 写入缓存
    public void setWithLogicalExpire(String key, Object value, Long time, TimeUnit unit){
        //设置逻辑过期
        RedisData redisData=new RedisData();
        redisData.setData(value);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(unit.toSeconds(time)));
        //写入redis
        stringRedisTemplate.opsForValue().set(key,JSONUtil.toJsonStr(redisData));
    }
    //解决缓存穿透
    public <R, ID> R queryWithPassThrough
            (String keyPrefix, ID id, Class<R> type, Function<ID,R> dbFallBack,Long time,TimeUnit unit){
        String key=keyPrefix+id;
        //1.从redis中查询缓存
        String jsonStr = stringRedisTemplate.opsForValue().get(key);
        //2.查询到的结果不为空，则返回缓存
        if (StrUtil.isNotBlank(jsonStr)){
            return JSONUtil.toBean(jsonStr,type);
        }
        //3.判断是否为空,不为空则返回null值，避免缓存穿透问题
        if (jsonStr!=null){
            return null;
        }
        //4.为null就从数据库中查询
         R r= dbFallBack.apply(id);
        //5.判断是否为null若是null将空值也存入缓存避免缓存穿透
        if (r==null){
            stringRedisTemplate.opsForValue().set(key,"",CACHE_NULL_TTL,TimeUnit.SECONDS);
        }
        //存在写入redis
        this.set(key,r,time,unit);
        return r;
    }




    //线程池
    private static final ExecutorService CACHE_REBUILD_EXECUTOR= Executors.newFixedThreadPool(10);



    public <R,ID> R queryWithLogicalExpire
            (String keyPrefix,ID id,Class<R> type,Function<ID,R> dbFallBack,Long time,TimeUnit unit){
        String redisKey=keyPrefix + id;
        //1.先从redis查询数据
        String shopJsonStr = stringRedisTemplate.opsForValue().get(redisKey);
        //2.命中直接返回
        if (StrUtil.isBlank(shopJsonStr)){
            return null;
        }
        //3.命中，需要先把json反序列化为对象
        RedisData redisData = JSONUtil.toBean(shopJsonStr, RedisData.class);
        JSONObject data =(JSONObject) redisData.getData();
        R r = JSONUtil.toBean(data, type);
        LocalDateTime expireTime = redisData.getExpireTime();
        //4.判断是否过期
        if (expireTime.isAfter(LocalDateTime.now())){
            //4.1未过期，直接返回
            return r;
        }

        //4.2已经过期,缓存重建
        //5.1获取互斥锁
        String lockKey=LOCK_SHOP_KEY+id;
        boolean isFlag = tryLock(lockKey);
        //5.2判断是否获取互斥锁成功
        if (isFlag){
            //5.3成功，获取独立线程，实现缓存重建
            CACHE_REBUILD_EXECUTOR.submit(()->{
                try {
                    R r1 = dbFallBack.apply(id);
                    setWithLogicalExpire(redisKey,r1,time,unit);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }finally {
                    unLock(lockKey);
                }
            });

        }
        //5.4失败，返回信息
        return r;
    }
    private boolean tryLock(String key){
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(flag);
    }
    //删除锁
    private void unLock(String key){
        stringRedisTemplate.delete(key);
    }

}
